// src/pages/RoleUserList/components/SelectUserModal.tsx
import React, {useState, useRef, useEffect} from 'react';
import {callApi, handleProTableRequest} from '@/utils/request'; // 根据你的实际路径调整

import {
    Button,
    Space,
    Modal,
    Tag,
    Tabs, message,
} from 'antd';
import {
    ProTable,
    ProColumns,
} from '@ant-design/pro-components';
import {
    getRoleListByUser,
    addUserRole,
    deleteUserRole,
} from '@/services/roleUser';

import {
    getRoleListByPermission,
} from '@/services/role';

import {
    addRolePermission,
} from '@/services/permission';

// 定义用户数据类型
type RoleItem = {
    userId: number;
    roleId: number;
    roleName: string;
    bindStatus: number;
    bindStatusDesc: string;
};

type SelectRoleModalProps = {
    visible: boolean;
    canOperate: boolean;
    queryType: number;// 1-用户，2-资源
    curPermissionId?: number;
    curPermissionName?: string;

    curUserId?: number;
    curUserRealName?: string;
    onOk: () => void;
    onCancel: () => void;
};

type RoleQueryParams = {
    userId: number;
    permissionId: number;
    bindStatus?: number;
    pageNum: number;
    pageSize: number;
    roleName?: string;
};

const SelectRoleModal: React.FC<SelectRoleModalProps> = ({
                                                             visible,
                                                             canOperate,
                                                             queryType,
                                                             curPermissionId,
                                                             curPermissionName,
                                                             curUserId,
                                                             curUserRealName,
                                                             onOk,
                                                             onCancel,
                                                         }) => {
    const actionRef = useRef<any>(null);

    // 用户列表列定义
    const baseColumns: ProColumns<RoleItem>[] = [
        {
            title: '角色编号',
            dataIndex: 'roleId',
            align: 'center',
            width: 120,
            search: false,
        },
        {
            title: '角色名称',
            dataIndex: 'roleName',
            align: 'center',
            width: 120,
        },
        {
            title: '绑定状态',
            dataIndex: 'bindStatus',
            align: 'center',
            valueType: 'select',
            width: 120,
            valueEnum: {
                '-1': {text: '全部'},
                '1': {text: '已绑定'},
            },
            fieldProps: {
                allowClear: false,
            },
            initialValue: '-1',
            render: (_, record) => (
                <Tag color={record.bindStatus === 1 ? 'success' : 'default'}>
                    {record.bindStatusDesc}
                </Tag>
            ),
        },
    ];

    // ✅ 条件添加“操作”列
    const columns = [...baseColumns];
    if (canOperate) {
        columns.push({
            title: '操作',
            dataIndex: 'option',
            valueType: 'option',
            width: 120,
            fixed: 'right',
            render: (_, record) => (
                <Space>
                    {record.bindStatus === 1 ? (
                        <Button
                            type="link"
                            size="small"
                            danger
                            onClick={() => handleUnbind(record)}
                        >
                            解绑
                        </Button>
                    ) : (
                        <Button
                            type="link"
                            size="small"
                            onClick={() => handleBind(record)}
                        >
                            绑定
                        </Button>
                    )}
                </Space>
            ),
        });
    }

    const handleOk = () => {
        onOk();
    };

    const handleCancel = () => {
        onCancel();
    };

    const handleBind = async (record: RoleItem) => {
        if (queryType == 1) {
            await handleBindUser(record)
        } else if (queryType == 2) {
            message.error("暂不支持在此页面绑定权限")
        }
    };

    const handleBindUser = async (record: RoleItem) => {
        const result = await callApi(
            () => addUserRole({userId: curUserId!, roleId: record.roleId}),
            {successMsg: '绑定成功', errorMsg: '绑定失败'}
        );
        if (result && actionRef.current) {
            await actionRef.current.reload();
        }
    };

    const handleUnbind = async (record: RoleItem) => {
        if (queryType == 1) {
            await handleUnbindUser(record)
        } else if (queryType == 2) {
            message.error("暂不支持在此页面解绑权限")
        }
    };

    const handleUnbindUser = async (record: RoleItem) => {
        const result = await callApi(
            () => deleteUserRole({userId: curUserId!, roleId: record.roleId}),
            {successMsg: '解绑成功', errorMsg: '解绑失败'}
        );
        if (result && actionRef.current) {
            await actionRef.current.reload();
        }
    };


    return (
        <Modal
            title={`${queryType === 1 ? curUserRealName : curPermissionName} 角色管理`}
            open={visible}
            onOk={handleOk}
            onCancel={handleCancel}
            width={1000}
            bodyStyle={{padding: 0}}
            destroyOnClose
        >
            <ProTable<RoleItem, RoleQueryParams>
                actionRef={actionRef}
                rowKey="roleId"
                search={{
                    labelWidth: 'auto',
                    defaultCollapsed: false,
                    // 自定义搜索项
                    optionRender: ({searchText, resetText}, {form}) => [
                        <Button key="search" type="primary" onClick={() => form?.submit?.()}>
                            {searchText}
                        </Button>,
                        <Button key="reset" onClick={() => {
                            form?.resetFields?.();
                            form?.submit?.();
                        }}>
                            {resetText}
                        </Button>,
                    ],
                }}
                request={async (params, sorter, filter) => {
                    // 前端传入的 bindStatus：-1 表示“全部”，1 表示“已绑定”
                    // 后端接口需支持 bindStatus = -1 表示不传该条件（或传 null）
                    const queryParams: RoleQueryParams = {
                        userId: curUserId!,
                        permissionId: curPermissionId!,
                        pageNum: params.current || 1,
                        pageSize: params.pageSize || 10,
                        roleName: params.roleName,
                        bindStatus: params.bindStatus, // -1 时不清除条件
                    };
                    if (queryType === 1) {
                        return handleProTableRequest<RoleItem>(
                            () => getRoleListByUser(queryParams),
                            {errorMsg: '获取角色列表失败'}
                        );
                    } else {
                        return handleProTableRequest<RoleItem>(
                            () => getRoleListByPermission(queryParams),
                            {errorMsg: '获取角色列表失败'}
                        );
                    }
                }}
                columns={[
                    ...columns,
                ]}
                pagination={{
                    defaultPageSize: 10,
                    showSizeChanger: true,
                    showQuickJumper: true,
                    pageSizeOptions: ['10', '20', '30', '50'],
                }}
            />
        </Modal>
    );
};

export default SelectRoleModal;